package com.chuangshu.chuangshuteam.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chuangshu.chuangshuteam.entity.TeamInvitation;
import com.chuangshu.chuangshuteam.entity.TeamMember;
import com.chuangshu.chuangshuteam.mapper.TeamInvitationMapper;
import com.chuangshu.chuangshuteam.mapper.TeamMemberMapper;
import com.chuangshu.chuangshuteam.service.TeamInvitationService;
import com.chuangshu.chuangshuteam.service.UsersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class TeamInvitationServiceImpl implements TeamInvitationService {

    @Autowired
    private TeamInvitationMapper teamInvitationMapper;

    @Autowired
    private TeamMemberMapper teamMemberMapper;

    @Autowired
    private UsersService usersService;

    /**
     * 创建邀请
     */
    @Override
    @Transactional
    public TeamInvitation createInvitation(Long inviterId, String inviteeOpenid, String inviteeName, String direction) {
        // 检查邀请人是否有权限创建邀请
        if (!canCreateInvitation(inviterId)) {
            throw new SecurityException("无权限创建邀请");
        }

        // 生成唯一邀请码
        String inviteCode = generateInviteCode();

        TeamInvitation invitation = new TeamInvitation();
        invitation.setTeamId(1L); // 默认团队ID
        invitation.setInviterId(inviterId);
        invitation.setInviteeOpenid(inviteeOpenid);
        invitation.setInviteeName(inviteeName);
        invitation.setDirection(direction);
        invitation.setStatus("pending");
        invitation.setInviteCode(inviteCode);
        invitation.setExpiresAt(LocalDateTime.now().plusDays(7)); // 7天后过期

        teamInvitationMapper.insert(invitation);

        log.info("创建团队邀请: inviterId={}, inviteeOpenid={}, direction={}",
                inviterId, inviteeOpenid, direction);

        return invitation;
    }

    /**
     * 接受邀请
     */
    @Override
    @Transactional
    public TeamMember acceptInvitation(String inviteCode, Long userId) {
        // 查找有效的邀请
        TeamInvitation invitation = findValidInvitation(inviteCode);
        if (invitation == null) {
            throw new IllegalArgumentException("邀请码无效或已过期");
        }

        // 检查用户是否已加入团队
        if (usersService.isUserInTeam(userId)) {
            throw new IllegalStateException("用户已加入团队");
        }

        // 更新邀请状态
        invitation.setStatus("accepted");
        invitation.setInviteeId(userId);
        teamInvitationMapper.updateById(invitation);

        // 创建团队成员记录
        TeamMember teamMember = new TeamMember();
        teamMember.setUserId(userId);
        teamMember.setTeamId(1L); // 默认团队ID
        teamMember.setDirection(invitation.getDirection());
        teamMember.setRoleId(3L); // 默认角色：普通成员

        teamMemberMapper.insert(teamMember);

        log.info("用户接受团队邀请: userId={}, invitationId={}", userId, invitation.getId());

        return teamMember;
    }

    /**
     * 获取用户的邀请列表
     */
    @Override
    public List<TeamInvitation> getUserInvitations(Long userId) {
        LambdaQueryWrapper<TeamInvitation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeamInvitation::getInviteeId, userId)
                .or()
                .eq(TeamInvitation::getInviterId, userId);

        return teamInvitationMapper.selectList(queryWrapper);
    }

    /**
     * 撤销邀请
     */
    @Override
    public boolean revokeInvitation(Long invitationId, Long userId) {
        TeamInvitation invitation = teamInvitationMapper.selectById(invitationId);
        if (invitation == null) {
            return false;
        }

        // 检查权限：只有邀请人或管理员可以撤销
        if (!invitation.getInviterId().equals(userId) &&
                !usersService.isAdmin(userId)) {
            throw new SecurityException("无权限撤销此邀请");
        }

        invitation.setStatus("revoked");
        int result = teamInvitationMapper.updateById(invitation);

        return result > 0;
    }

    /**
     * 检查邀请是否有效
     */
    @Override
    public boolean isInvitationValid(String inviteCode) {
        TeamInvitation invitation = findValidInvitation(inviteCode);
        return invitation != null;
    }

    /**
     * 检查用户是否有权限创建邀请
     */
    private boolean canCreateInvitation(Long userId) {
        // 管理员和方向负责人可以创建邀请
        // 这里简化实现，实际应该根据角色判断
        return usersService.isUserInTeam(userId); // 团队成员都可以创建邀请
    }

    /**
     * 生成唯一邀请码
     */
    private String generateInviteCode() {
        return UUID.randomUUID().toString().substring(0, 8).toUpperCase();
    }

    /**
     * 查找有效的邀请
     */
    private TeamInvitation findValidInvitation(String inviteCode) {
        LambdaQueryWrapper<TeamInvitation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeamInvitation::getInviteCode, inviteCode)
                .eq(TeamInvitation::getStatus, "pending")
                .gt(TeamInvitation::getExpiresAt, LocalDateTime.now());

        return teamInvitationMapper.selectOne(queryWrapper);
    }
}